package org.jeecg.modules.business.controller;

import java.sql.Time;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.business.entity.BusDictItem;
import org.jeecg.modules.business.entity.BusNightTrial;
import org.jeecg.modules.business.entity.BusSalesPersonPost;
import org.jeecg.modules.business.service.IBusNightTrialService;
import org.jeecg.modules.business.util.DateTimeToCronUtils;
import org.jeecg.modules.quartz.entity.QuartzJob;
import org.jeecg.modules.quartz.service.IQuartzJobService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

 /**
 * @Description: 夜审设置
 * @Author: jeecg-boot
 * @Date:   2023-03-10
 * @Version: V1.0
 */
@Api(tags="夜审设置")
@RestController
@RequestMapping("/business/busNightTrial")
@Slf4j
public class BusNightTrialController extends JeecgController<BusNightTrial, IBusNightTrialService> {
	@Autowired
	private IBusNightTrialService busNightTrialService;

	 @Resource
	 private IQuartzJobService quartzJobService;
	/**
	 * 分页列表查询
	 *
	 * @param busNightTrial
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "夜审设置-分页列表查询")
	@ApiOperation(value="夜审设置-分页列表查询", notes="夜审设置-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<BusNightTrial>> queryPageList(BusNightTrial busNightTrial,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<BusNightTrial> queryWrapper = QueryGenerator.initQueryWrapper(busNightTrial, req.getParameterMap());
		Page<BusNightTrial> page = new Page<BusNightTrial>(pageNo, pageSize);
		IPage<BusNightTrial> pageList = busNightTrialService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param busNightTrial
	 * @return
	 */
	@AutoLog(value = "夜审设置-添加")
	@ApiOperation(value="夜审设置-添加", notes="夜审设置-添加")
	//@RequiresPermissions("business:bus_night_trial_info:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody BusNightTrial busNightTrial) {
		if(busNightTrial.getTenantId() == null || busNightTrial.getTenantId().equals("")){
			LoginUser user = TokenUtils.getAuthUser();
			if(user.getRelTenantIds() != null && !user.getRelTenantIds().equals("")){
				busNightTrial.setTenantId(user.getRelTenantIds());
			} else {
				throw new JeecgBootException("当前登录人租户信息错误");
			}
		}
		busNightTrialService.save(busNightTrial);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param busNightTrial
	 * @return
	 */
	@AutoLog(value = "夜审设置-编辑")
	@ApiOperation(value="夜审设置-编辑", notes="夜审设置-编辑")
	//@RequiresPermissions("business:bus_night_trial_info:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody BusNightTrial busNightTrial) {
		if(busNightTrial.getTenantId() == null || busNightTrial.getTenantId().equals("")){
			LoginUser user = TokenUtils.getAuthUser();
			if(user.getRelTenantIds() != null && !user.getRelTenantIds().equals("")){
				busNightTrial.setTenantId(user.getRelTenantIds());
			} else {
				throw new JeecgBootException("当前登录人租户信息错误");
			}
		}
		BusNightTrial editModel = busNightTrialService.getById(busNightTrial.getId());
		editModel.setAutoCheck(busNightTrial.getAutoCheck());
		editModel.setSetNightTrialTime(busNightTrial.getSetNightTrialTime());
		editModel.setAutoHand(busNightTrial.getAutoHand());
		busNightTrialService.updateById(editModel);
		return Result.OK("编辑成功!");
	}

	 /**
	  *  编辑
	  *
	  * @param busNightTrial
	  * @return
	  */
	 @AutoLog(value = "夜审设置-编辑")
	 @ApiOperation(value="夜审设置-编辑", notes="夜审设置-编辑")
	 //@RequiresPermissions("business:bus_night_trial_info:edit")
	 @RequestMapping(value = "/editAutoCheck", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<BusNightTrial> editAutoCheck(@RequestBody BusNightTrial busNightTrial) {
		 if(busNightTrial.getTenantId() == null || busNightTrial.getTenantId().equals("")){
			 LoginUser user = TokenUtils.getAuthUser();
			 if(user.getRelTenantIds() != null && !user.getRelTenantIds().equals("")){
				 busNightTrial.setTenantId(user.getRelTenantIds());
			 } else {
				 throw new JeecgBootException("当前登录人租户信息错误");
			 }
		 }
		 QuartzJob job = quartzJobService.getOne(Wrappers.<QuartzJob>lambdaQuery()
				 .eq(QuartzJob::getParameter, busNightTrial.getHotelId()).eq(QuartzJob::getTaskType, 1).last("limit 1"));
		 if (busNightTrial.getId() != null && !busNightTrial.getId().equals("")){
			 BusNightTrial editModel = busNightTrialService.getById(busNightTrial.getId());
			 editModel.setAutoCheck(busNightTrial.getAutoCheck());
			 busNightTrialService.updateById(editModel);
			 boolean b = editModel.getAutoCheck() == 0 ? quartzJobService.pause(job) : quartzJobService.resumeJob(job);
			 return Result.OK(editModel);
		 }else{
			 busNightTrial.setDelFlag(CommonConstant.DEL_FLAG_0);
			 busNightTrial.setAutoHand(1);
			 Time _time = Time.valueOf("06:00:00");
			 busNightTrial.setSetNightTrialTime(_time);
			 busNightTrialService.save(busNightTrial);
			 quartzJobService.resumeJob(job);
			 return Result.OK(busNightTrial);
		 }
	 }

	 /**
	  *  时间编辑
	  *
	  * @param busNightTrial
	  * @return
	  */
	 @AutoLog(value = "夜审设置-时间编辑")
	 @ApiOperation(value="夜审设置-编辑", notes="夜审设置-编辑")
	 //@RequiresPermissions("business:bus_night_trial_info:edit")
	 @RequestMapping(value = "/editNightTrialTime", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<BusNightTrial> editNightTrialTime(@RequestBody BusNightTrial busNightTrial) {
		 if(busNightTrial.getTenantId() == null || busNightTrial.getTenantId().equals("")){
			 LoginUser user = TokenUtils.getAuthUser();
			 if(user.getRelTenantIds() != null && !user.getRelTenantIds().equals("")){
				 busNightTrial.setTenantId(user.getRelTenantIds());
			 } else {
				 throw new JeecgBootException("当前登录人租户信息错误");
			 }
		 }
		 QuartzJob job = quartzJobService.getOne(Wrappers.<QuartzJob>lambdaQuery()
				 .eq(QuartzJob::getParameter, busNightTrial.getHotelId()).eq(QuartzJob::getTaskType, 1).last("limit 1"));
//		 Time _time = Time.valueOf(busNightTrial.getSetNightTrialTime());
//		 busNightTrial.setSetNightTrialTime(_time);
		 if (busNightTrial.getId() != null && !busNightTrial.getId().equals("")){
			 BusNightTrial editModel = busNightTrialService.getById(busNightTrial.getId());
			 editModel.setSetNightTrialTime(busNightTrial.getSetNightTrialTime());
			 busNightTrialService.updateById(editModel);
			 job.setCronExpression(DateTimeToCronUtils.getCron(editModel.getSetNightTrialTime(), DateTimeToCronUtils.EVERYDAY));
			 quartzJobService.resumeJob(job);
			 return Result.OK(editModel);
		 } else {
			 busNightTrial.setDelFlag(CommonConstant.DEL_FLAG_0);
			 busNightTrial.setAutoHand(1);
			 busNightTrial.setAutoCheck(1);
			 busNightTrialService.save(busNightTrial);
			 quartzJobService.resumeJob(job);
			 return Result.OK(busNightTrial);
		 }
	 }

	 /**
	  *  转脏房编辑
	  *
	  * @param busNightTrial
	  * @return
	  */
	 @AutoLog(value = "夜审设置-转脏房编辑")
	 @ApiOperation(value="夜审设置-编辑", notes="夜审设置-编辑")
	 //@RequiresPermissions("business:bus_night_trial_info:edit")
	 @RequestMapping(value = "/editAutoHand", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<BusNightTrial> editAutoHand(@RequestBody BusNightTrial busNightTrial) {
		 if(busNightTrial.getTenantId() == null || busNightTrial.getTenantId().equals("")){
			 LoginUser user = TokenUtils.getAuthUser();
			 if(user.getRelTenantIds() != null && !user.getRelTenantIds().equals("")){
				 busNightTrial.setTenantId(user.getRelTenantIds());
			 } else {
				 throw new JeecgBootException("当前登录人租户信息错误");
			 }
		 }
		 if (busNightTrial.getId() != null && !busNightTrial.getId().equals("")){
			 BusNightTrial editModel = busNightTrialService.getById(busNightTrial.getId());
			 editModel.setAutoHand(busNightTrial.getAutoHand());
			 editModel.setRoomToDirty(busNightTrial.getRoomToDirty());
			 busNightTrialService.updateById(editModel);
			 return Result.OK(editModel);
		 }else{
			 busNightTrial.setDelFlag(CommonConstant.DEL_FLAG_0);
			 busNightTrial.setAutoHand(1);
			 Time _time = Time.valueOf("06:00:00");
			 busNightTrial.setSetNightTrialTime(_time);
			 busNightTrialService.save(busNightTrial);
			 return Result.OK(busNightTrial);
		 }
	 }

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "夜审设置-通过id删除")
	@ApiOperation(value="夜审设置-通过id删除", notes="夜审设置-通过id删除")
	//@RequiresPermissions("business:bus_night_trial_info:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		busNightTrialService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "夜审设置-批量删除")
	@ApiOperation(value="夜审设置-批量删除", notes="夜审设置-批量删除")
	//@RequiresPermissions("business:bus_night_trial_info:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.busNightTrialService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "夜审设置-通过id查询")
	@ApiOperation(value="夜审设置-通过id查询", notes="夜审设置-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<BusNightTrial> queryById(@RequestParam(name="id",required=true) String id) {
		BusNightTrial busNightTrial = busNightTrialService.getById(id);
		if(busNightTrial==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(busNightTrial);
	}


	 /**
	  * 通过hotelId查询
	  *
	  * @param hotelId
	  * @return
	  */
	 //@AutoLog(value = "夜审设置-通过hotelId查询")
	 @ApiOperation(value="夜审设置-通过hotelId查询", notes="夜审设置-通过hotelId查询")
	 @GetMapping(value = "/queryByHotelId")
	 public Result<BusNightTrial> queryByHotelId(@RequestParam(name="hotelId",required=true) String hotelId) {
		 QueryWrapper<BusNightTrial> queryWrapper = new QueryWrapper<BusNightTrial>();
		 queryWrapper.eq("hotel_id", hotelId);
		 BusNightTrial busNightTrial = busNightTrialService.getOne(queryWrapper);
		 if(busNightTrial==null) {
			 return Result.error("");
		 }
		 return Result.OK(busNightTrial);
	 }

    /**
    * 导出excel
    *
    * @param request
    * @param busNightTrial
    */
    //@RequiresPermissions("business:bus_night_trial_info:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BusNightTrial busNightTrial) {
        return super.exportXls(request, busNightTrial, BusNightTrial.class, "夜审设置");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("business:bus_night_trial_info:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, BusNightTrial.class);
    }

}
